package com.bt.lms.ui.action.school_education.stu_basic.BasicMes;


import com.alibaba.fastjson.JSON;
import com.bt.lms.constants.BOConstant;
import com.bt.lms.constants.StuStatusBizTypeConstant;
import com.bt.lms.entity.StuBasicInfo;
import com.bt.lms.network.msg.ReqMsg;
import com.bt.lms.network.msg.RespMsg;
import com.bt.lms.ui.vo.school_education.basic_mes.BasicMesVo;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.scene.control.*;
import javafx.scene.layout.VBox;
import org.apache.commons.beanutils.BeanUtils;

import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.net.Socket;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 基本信息里编辑的保存验证事件
 */
public class EditBasicMesVerify implements EventHandler {

    private VBox vBox;

    public EditBasicMesVerify(VBox totalVBox) {
        this.vBox = totalVBox;
    }

    /**
     * 保存编辑学员基本信息
     *
     * @param event
     */
    @Override
    public void handle(Event event) {

        //1.获取用户输入，返回一个定义的VO，里面承载着用户的输入
        BasicMesVo basicMesVo = getImport();
        //2.验证用户输入，给他vo对象，返回一个经过验证的 消息 对象
        String validateMsg = validateImport(basicMesVo);
        //3、组包 (根据自定义的网络消息协议)，inP:VO  outP:消息
        byte[] bytes = null;
        if (validateMsg == null) {
            //验证通过，组包
            bytes = handle2ReqMsg(basicMesVo);
        } else {
            //提示，程序终止
            return;
        }
        //4、组网(根据咱们自定义的网络连接交互规范来定义)inP：服务器的信息(ip,port......)
        Socket socket = getNet();
        //5、发送消息 ，inP:消息  outP:是否发送成功
        boolean flag = sendMsg(socket, bytes, basicMesVo);

    }

    /**
     * 发送消息
     *
     * @param socket     网
     * @param bytes      消息包
     * @param basicMesVo vo对象
     * @return 是否成功
     */
    private boolean sendMsg(Socket socket, byte[] bytes, BasicMesVo basicMesVo) {

//
        try {
            OutputStream out = socket.getOutputStream();
            out.write(bytes);
            out.flush();

            //接收响应消息
            InputStream in = socket.getInputStream();
            byte[] buf = new byte[1024];
            in.read(buf);

            RespMsg respMsg = RespMsg.toRespMsg(buf);
            String data = respMsg.getData();
            if (data != null) {
                Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
                alert.setContentText("保存成功");
                alert.show();
            }
            //界面回显


            //关闭资源
            out.close();
            socket.close();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }


        return true;
    }

    public static byte[] intToBytes(int value) {
        byte[] src = new byte[4];
        src[0] = (byte) ((value >> 24) & 0xFF);
        src[1] = (byte) ((value >> 16) & 0xFF);
        src[2] = (byte) ((value >> 8) & 0xFF);
        src[3] = (byte) (value & 0xFF);
        return src;

    }


    /**
     * 组建网络
     *
     * @return 网络
     */
    private Socket getNet() {
        String ip = "127.0.0.1";
        Integer port = 8888;
        Socket socket = null;
        try {
            socket = new Socket(ip, port);

        } catch (IOException e) {
            e.printStackTrace();
        }


        return socket;
    }

    /**
     * 将用户的输入转成我们要的格式，json格式
     *
     * @param basicMesVo 用户输入的VO对象
     * @return 请求消息模型
     */
    private byte[] handle2ReqMsg(BasicMesVo basicMesVo) {
        //业务类型
        ReqMsg reqMsg = new ReqMsg();
        reqMsg.setBizType(StuStatusBizTypeConstant.BASIC_INFO_BIZ_TYPE);
        StuBasicInfo stuBasicInfo = new StuBasicInfo();
        byte[] bytes = null;
        try {
            BeanUtils.copyProperties(stuBasicInfo, basicMesVo);
            stuBasicInfo.setId(1L);
            String basicInfoStr = JSON.toJSONString(stuBasicInfo);
            reqMsg.setData(basicInfoStr);
            bytes = reqMsg.toBytes();
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }


        return bytes;
    }

    /**
     * \
     * 验证用户输入的是否合法
     *
     * @param basicMesVo 用户输入的消息
     * @return 验证的结果
     */
    private String validateImport(BasicMesVo basicMesVo) {
        String mes = "";
        //学员编号验证
        String stuNo = basicMesVo.getNo();
        //判断，如果没填写
        String noBlackMsg = "学员编号必填，请输入\r\n";
        String noLenMsg = "学员编号在1-24个长度之间，请重新输入\r\n";

        if (stuNo.equals("")) {
            mes += noBlackMsg;
        } else {
            if (stuNo.length() > 24) {
                mes += noLenMsg;
            }
        }


        //姓名验证
        String name = basicMesVo.getName();
        //判断，如果没填写
        String nameBlackMsg = "姓名为必填，请输入\r\n";
        String nameLenMsg = "姓名在1-24之间，请重新输入\r\n";
        if (name.equals("")) {
            mes += nameBlackMsg;
        } else {
            //判断，如果有内容，是否符合规范
            if (name.length() > 24) {
                mes += nameLenMsg;
            }
        }

        //性别验证
        Integer sex = basicMesVo.getSex();
        //判断，如果没选择
        String sexBlackMsg = "性别为必填，请选择\r\n";
        if (sex == null) {
            mes += sexBlackMsg;
        }

        //出生日期验证
        LocalDate birthDate = basicMesVo.getBirthTime();
        if (birthDate == null) {
            mes += "出生日期为必填，请输入\r\n";
        } else {
            //判断，如果有内容，是否符合规范
            int birthDayValueYear = birthDate.getYear();
            LocalDateTime localDateTime = LocalDateTime.now();
            int localDateTimeYear = localDateTime.getYear();
            if (birthDayValueYear > localDateTimeYear || localDateTimeYear - birthDayValueYear > 130) {
                mes += "您输入的出生日期超过了现有时间，请核验并重新输入\r\n";
            }
        }

        //籍贯验证

        if (basicMesVo.getNativePlace() == null) {
            mes += "籍贯为必填，请您输入\r\n";
        } else {
            String nativePlace = basicMesVo.getNativePlace();
        }

        //民族验证
        //判断，如果没选择
        if (basicMesVo.getNation() == null) {
            mes += "民族为必填，请输入\r\n";
        } else {
            String nation = basicMesVo.getNation();
            int oi = 0;

        }


        //出生地验证
        //判断，如果没输入
        String birthplace = basicMesVo.getBirthplace();
        if (birthplace.equals("")) {
            mes += "出生地为必填，请输入\r\n";
        }
        //判断，如果有内容，是否符合规范
        if (birthplace.length() > 32) {
            mes += "出生地信息在1-32位之间，请核验并重新输入\r\n";
        }

        //证件类型验证
        //判断，如果没输入
        if (!(basicMesVo.getIdType() == null)) {
            String idType = basicMesVo.getIdType();
            if (idType.equals("")) {
                mes += "证件类型为必填，请选择\r\n";
            }
        }


        //证件号码
        String idCard = basicMesVo.getIdCard();
        //判断，如果没输入
        if (idCard.equals("")) {
            mes += "证件号码为必填，请输入\r\n";
        } else {
            // 判断，如果证件类型是身份证，查看是否符合规范
            try {
                if (basicMesVo.getIdType().equals("身份证")) {
                    int idNoTFLength = idCard.length();
                    if (!(idNoTFLength == 18)) {
                        int i = Integer.parseInt(idCard);
                        mes += "身份证号码只能为18位，请核验并重新输入\r\n";
                    }
                }
            } catch (NumberFormatException e) {
                mes += "证件号码只能为18位的数字或17位数字加大写X，请核验并重新输入\r\n";
            }
        }


        //婚姻状况
        Integer maritalStatus = basicMesVo.getMaritalStatus();
        if (maritalStatus == null) {
            mes += "婚姻状况为必填，请选择\r\n";
        }


        //政治面貌
        Integer politicsStatus = basicMesVo.getPoliticsStatus();
        //判断，如果没选择
        if (politicsStatus == null) {
            mes += "政治面貌为必填，请选择\r\n";
        }

        //上传照片验证
        if (!(basicMesVo.getPicture() == null)) {
            String editPhoto = basicMesVo.getPicture();
            if (!editPhoto.endsWith("png") && !editPhoto.endsWith("jpeg") && !editPhoto.endsWith("webp") && !editPhoto.endsWith("jpg") &&
                    !editPhoto.endsWith(".JPG")) {
                mes += "您上传的照片类型不符合规范\r\n";
            }
        }


        //---------------------更多基本信息-----非必填
        //英文名字
        String englishName = basicMesVo.getEnglishName();
        if (!englishName.equals("")) {
            if (englishName.length() > 24) {
                mes += "英文名字在1-24位之间\r\n";
            }
        }

        //姓名拼音
        String namePhoneticize = basicMesVo.getNamePhoneticize();
        if (!namePhoneticize.equals("")) {
            if (namePhoneticize.length() > 24) {
                mes += "姓名拼音在1-24位之间\r\n";
            }
        }

        //曾用名
        String formerName = basicMesVo.getFormerName();
        if (!formerName.equals("")) {
            if (formerName.length() > 24) {
                mes += "曾用名在1-24位之间\r\n";
            }
        }

        //信仰宗教
//        Integer faith = basicMesVo.getFaith();
//        if (!faith.equals("")){
//
//        }

        //国籍/地区
        String nationality = basicMesVo.getNationality();
        if (!nationality.equals("")) {
            if (nationality.length() > 32) {
                mes += "国籍/地区在1-32位之间\r\n";
            }
        }

        //港澳台侨外
//        Integer alien = basicMesVo.getAlien();


        //健康状况

        //血型

        //身份证有效期
        //起

        if (!(basicMesVo.getStartIDCardValidity() == null)) {
            int startYear = basicMesVo.getStartIDCardValidity().getYear();
            LocalDate now = LocalDate.now();
            int nowYear = now.getYear();
            if (startYear > nowYear) {
                mes += "身份证起始时间要在当前日期之前\r\n";
            }
        }

        //止
        if (!(basicMesVo.getStopIDCardValidity() == null)) {
            int startYear = basicMesVo.getStartIDCardValidity().getYear();
            int stopYear = basicMesVo.getStopIDCardValidity().getYear();
//            LocalDate now = LocalDate.now();
//            int nowYear = now.getYear();
            if (startYear > stopYear) {
                mes += "到...的时间要在起始时间之后\r\n";
            }
        }

        //是否独生子女

        if (!(mes.equals(""))) {
            //总的弹出框
            Alert alert = new Alert(Alert.AlertType.WARNING);
            alert.setContentText(mes);
            alert.show();

        }
        if (mes.equals("")) {
            mes = null;
        }


        return mes;
    }

    /**
     * 获取用户的输入
     *
     * @return 有用户输入的VO
     */
    private BasicMesVo getImport() {
        //学员编号验证
        TextField noTF = (TextField) this.vBox.lookup("#noTF");
        //姓名
        TextField nameTF = (TextField) this.vBox.lookup("#nameTF");
        //性别验证
        ComboBox sexCB = (ComboBox) this.vBox.lookup("#sexTF");
        //出生日期验证
        DatePicker birthDay = (DatePicker) this.vBox.lookup("#birthDayDP");
        //籍贯验证
        //省
        ComboBox nativeTF = (ComboBox) this.vBox.lookup("#nativeTF");
        //市
        ComboBox city = (ComboBox) this.vBox.lookup("#city");
        //县
        ComboBox county = (ComboBox) this.vBox.lookup("#county");
        //民族验证
        ComboBox nationTF = (ComboBox) this.vBox.lookup("#nationTF");
        //出生地验证
        TextField birTF = (TextField) this.vBox.lookup("#birTF");
        //证件类型
        ComboBox IDTF = (ComboBox) this.vBox.lookup("#IDTF");
        //证件号码验证
        TextField IDNoTF = (TextField) this.vBox.lookup("#IDNoTF");
        //婚姻状况验证
        ComboBox maritalCB = (ComboBox) this.vBox.lookup("#maritalCB");
        //政治面貌验证
        ComboBox politicsCB = (ComboBox) this.vBox.lookup("#politicsCB");

        //英文名字验证
        TextField englishTF = (TextField) this.vBox.lookup("#englishTF");
        //姓名拼音验证
        TextField nameSpellTF = (TextField) this.vBox.lookup("#nameSpellTF");
        //曾用名验证
        TextField onceNameTF = (TextField) this.vBox.lookup("#onceNameTF");
        //信仰宗教验证
        ComboBox faithCB = (ComboBox) this.vBox.lookup("#faithCB");
        //国籍/地区验证
        TextField nationalityTF = (TextField) this.vBox.lookup("#nationalityTF");
        //港澳台侨外验证
        RadioButton yesRDB = (RadioButton) this.vBox.lookup("#yesRDB");
        RadioButton noRDB = (RadioButton) this.vBox.lookup("#noRDB");
        //健康状况验证
        ComboBox healthCB = (ComboBox) this.vBox.lookup("#healthCB");
        //血型验证
        ComboBox bloodCB = (ComboBox) this.vBox.lookup("#bloodCB");
        //身份证有效期验证
        DatePicker startDP = (DatePicker) this.vBox.lookup("#startDP");
        DatePicker stopDp = (DatePicker) this.vBox.lookup("#stopDp");
        //是否生子女
        RadioButton yesRDBtn = (RadioButton) this.vBox.lookup("#yesRDBtn");
        RadioButton noRDBtn = (RadioButton) this.vBox.lookup("#noRDBtn");


        //封装成VO对象
        BasicMesVo basicMesVo = new BasicMesVo();

        //编号
        String noStr = noTF.getText().trim();
        basicMesVo.setNo(noStr);

        //姓名
        String nameStr = nameTF.getText().trim();
        basicMesVo.setName(nameStr);

        //性别
        if (!(sexCB.getValue() == null)) {
            String sexCBValue = (String) sexCB.getValue();
            Integer level = -1;
            switch (sexCBValue) {
                case "男":
                    level = BOConstant.STU_BASIC_INFO_SEX_MAN;
                    break;
                case "女":
                    level = BOConstant.STU_BASIC_INFO_SEX_GIRL;
                    break;
            }
            basicMesVo.setSex(level);
        }


        //出生日期
        if (!(birthDay.getValue() == null)) {
            LocalDate birthDayValue = birthDay.getValue();
            String toString = birthDayValue.toString();
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate parse = LocalDate.parse(toString, dateTimeFormatter);
            basicMesVo.setBirthTime(parse);
        }


        //籍贯
        //省
        String nativeTFValue = (String) nativeTF.getValue();
        //市
        String cityValue = (String) city.getValue();
        //县
        String countyValue = (String) county.getValue();
        String nativeStr = nativeTFValue + cityValue + countyValue;
        basicMesVo.setNativePlace(nativeStr);


        //民族
        String nationStr = (String) nationTF.getValue();
        basicMesVo.setNation(nationStr);

        //出生地
        String birStr = birTF.getText().trim();
        basicMesVo.setBirthplace(birStr);

        //证件类型
        String idTypeStr = (String) IDTF.getValue();
        basicMesVo.setIdType(idTypeStr);

        //证件号码
        String idNoStr = IDNoTF.getText().trim();
        basicMesVo.setIdCard(idNoStr);

        //婚姻状况
        if (!(maritalCB.getValue() == null)) {
            String maritalCBValue = (String) maritalCB.getValue();
            int marital = -1;
            switch (maritalCBValue) {
                case "未婚":
                    marital = BOConstant.STU_BASIC_INFO_MARITAL_STATUS_SPINSTERHOOD;
                    break;
                case "已婚":
                    marital = BOConstant.STU_BASIC_INFO_MARITAL_STATUS_MARITAL;
                    break;
            }
            basicMesVo.setMaritalStatus(marital);
        }


        //政治面貌
        if (!(politicsCB.getValue() == null)) {
            String politicsCBValue = (String) politicsCB.getValue();
            int politics = -1;
            switch (politicsCBValue) {
                case "党员员":
                    politics = BOConstant.STU_BASIC_INFO_POLITICS_STATUS_PARTY_MEMBER;
                    break;
                case "团员":
                    politics = BOConstant.STU_BASIC_INFO_POLITICS_STATUS_MEMBER;
                    break;
                case "其他":
                    politics = BOConstant.STU_BASIC_INFO_POLITICS_STATUS_ELSE;
                    break;
            }
            basicMesVo.setPoliticsStatus(politics);
        }

        //修改头像
        if (!(BasicMesEditAction.file == null)) {
            //修改头像验证
            File file = BasicMesEditAction.file;
            try {
                FileInputStream fileInputStream = new FileInputStream(file);
                int available = fileInputStream.available();
                byte[] bytes = new byte[available];
                fileInputStream.read(bytes);
                fileInputStream.close();
                //上传文件到系统的用户目录下，创建一个属于当前项目的文件夹
                String property = System.getProperty("user.home");
                String uploadPath = "/StudentManageSys/upload";
                String dirPath = property + uploadPath;
                File dirFile = new File(dirPath);
                if (!dirFile.exists()) {
                    dirFile.mkdirs();//如果不存在创建目录，文件夹
                }
                //上传
                String pathName = BasicMesEditAction.file.getName();
                String filePath = dirPath + File.separator + pathName;
                File file1 = new File(filePath);
                file1.createNewFile();
                //把内容写进去
                FileOutputStream fileOutputStream = new FileOutputStream(file1);
                fileOutputStream.write(bytes);
                fileOutputStream.close();
                basicMesVo.setPicture(filePath);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


        //英文姓名
        String englishNameStr = englishTF.getText().trim();
        basicMesVo.setEnglishName(englishNameStr);

        //姓名拼音
        String nameSpell = nameSpellTF.getText().trim();
        basicMesVo.setNamePhoneticize(nameSpell);

        //曾用名
        String onceName = onceNameTF.getText().trim();
        basicMesVo.setFormerName(onceName);

        //信仰宗教
        if (!(faithCB.getValue() == null)) {
            String faithCBValue = (String) faithCB.getValue();
            int faith = -1;
            switch (faithCBValue) {
                case "无宗教信仰":
                    faith = BOConstant.STU_BASIC_INFO_FAITH_NULLIFIDIAN;
                    break;
                case "佛教":
                    faith = BOConstant.STU_BASIC_INFO_FAITH_BUDDHISM;
                    break;
                case "伊斯兰教":
                    faith = BOConstant.STU_BASIC_INFO_FAITH_LSLAM;
                    break;
                case "基督教":
                    faith = BOConstant.STU_BASIC_INFO_FAITH_CHRISTIAN;
                    break;
                case "其他":
                    faith = BOConstant.STU_BASIC_INFO_FAITH_ELSE;
                    break;
            }
            basicMesVo.setFaith(faith);
        }


        //国籍/地区
        String nationality = nationalityTF.getText().trim();
        basicMesVo.setNationality(nationality);

        //港澳台侨外
        boolean yesSelected = yesRDB.isSelected();
        boolean noSelected = noRDB.isSelected();
        if (yesSelected) {
            basicMesVo.setIsAlien(BOConstant.STU_BASIC_INFO_IS_ALIEN_YES);
        } else if (noSelected) {
            basicMesVo.setIsAlien(BOConstant.STU_BASIC_INFO_IS_ALIEN_NO);
        }

        //健康状况
        if (!(healthCB.getValue() == null)) {
            String healthCBValue = (String) healthCB.getValue();
            int health = -1;
            switch (healthCBValue) {
                case "健康或良好":
                    health = BOConstant.STU_BASIC_INFO_PHYSICAL_CONDITION_HEALTH;
                    break;
                case "一般或较弱":
                    health = BOConstant.STU_BASIC_INFO_PHYSICAL_CONDITION_ORDINARY;
                    break;
                case "有慢性疾病":
                    health = BOConstant.STU_BASIC_INFO_PHYSICAL_CONDITION_CHRONIC_DISEASE;
                    break;
                case "残疾":
                    health = BOConstant.STU_BASIC_INFO_PHYSICAL_CONDITION_DISABILITY;
                    break;
            }
            basicMesVo.setPhysicalCondition(health);
        }


        //血型
        if (!(bloodCB.getValue() == null)) {
            String bloodCBValue = (String) bloodCB.getValue();
            int blood = -1;
            switch (bloodCBValue) {
                case "A型血":
                    blood = BOConstant.STU_BASIC_INFO_BLOOD_TYPE_A;
                    break;
                case "B型血":
                    blood = BOConstant.STU_BASIC_INFO_BLOOD_TYPE_B;
                    break;
                case "AB型血":
                    blood = BOConstant.STU_BASIC_INFO_BLOOD_TYPE_AB;
                    break;
                case "O型血":
                    blood = BOConstant.STU_BASIC_INFO_BLOOD_TYPE_O;
                    break;
                case "其他":
                    blood = BOConstant.STU_BASIC_INFO_BLOOD_TYPE_ELSE;
                    break;
            }
            basicMesVo.setBloodType(blood);

        }

        //身份证有效时间
        //起
        if (!(startDP.getValue() == null)) {
            LocalDate startDPValue = startDP.getValue();
            String startDPStr = startDPValue.toString();
            DateTimeFormatter startDPFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate startDPParse = LocalDate.parse(startDPStr, startDPFormatter);
            basicMesVo.setStartIDCardValidity(startDPParse);
        }


        //止
        if (!(stopDp.getValue() == null)) {
            LocalDate stopDpValue = stopDp.getValue();
            String stopDpStr = stopDpValue.toString();
            DateTimeFormatter stopDpFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate stopDpParse = LocalDate.parse(stopDpStr, stopDpFormatter);
            basicMesVo.setStopIDCardValidity(stopDpParse);
        }


        //是否独生子女
        boolean yesRDBtnSelected = yesRDBtn.isSelected();
        boolean noRDBtnSelected = noRDBtn.isSelected();
        if (yesRDBtnSelected) {
            basicMesVo.setOnlyChild(BOConstant.STU_BASIC_INFO_ONLY_CHILD_YES);
        } else if (noRDBtnSelected) {
            basicMesVo.setOnlyChild(BOConstant.STU_BASIC_INFO_ONLY_CHILD_NO);
        }


        return basicMesVo;
    }
}
